import {simplePost} from "@/utils/request";
import {msgSuccess} from "@/utils/alert";
import {ElMessageBox} from "element-plus";

interface Store {
    field: string,
    order: string
}

interface Page {
    total: number,
    currentPage: number,
    pageSize: number,
    pageSizes: Array<number>
}

export default class List {

    columns: Array<any>   // 列表字段

    url: string     // 请求url

    where: any   // 查询条件

    rawData: any = [] // 远程请求返回的原始数据

    items: any[] = []      // 表格数据

    key: string = 'id'      //  主键字段

    isPage: boolean = true   // 是否分页

    border: boolean = true   // 是否添加边框

    size: string = 'default'

    selectKeys: Array<any> = []     // 所有选中行的键【数组】

    sort: Store = {field: 'create_time', order: 'desc'}       // 排序字段

    isLazy: boolean = false  // 懒加载

    loading: boolean = false  // 页面加载状态

    currentRow: any = null     //  当前选中的行

    page: Page = {
        total: 0,
        currentPage: 1,
        pageSize: 10,
        pageSizes: [10, 30, 60, 100],
    }

    constructor({
                    url,
                    columns = [],
                    where = {},
                    key = 'id',
                    isPage = true,
                    border = true,
                    selectKeys = [],
                    sort = {field: 'create_time', order: 'desc'},
                    isLazy = false,
                    loading = true,
                    currentRow = null
                }: {
        url: string, columns: Array<any>, where?: any, key?: string, isPage?: boolean, border?: boolean,
        selectKeys?: Array<any>, sort?: Store, isLazy?: boolean, loading?: boolean, currentRow?: any
    }) {
        this.url = url
        this.columns = columns
        this.where = where
        this.key = key
        this.isPage = isPage
        this.border = border
        this.selectKeys = selectKeys
        this.sort = sort
        this.isLazy = isLazy
        this.loading = loading
        this.currentRow = currentRow
    }


    async getList() {

        this.loading = true

        let params = {
            page: this.page.currentPage,
            pageSize: this.page.pageSize,
            field: this.sort.field,
            order: this.sort.order,
            where: this.where,
        }

        let rd = await simplePost(this.url, params)

        this.rawData = rd;

        // 更新props.table数据
        if (this.isLazy) {
            // 只将第一层数据传递给列表
            let arr = []
            for (let vo of rd.items) {
                if (vo.level == 1) {
                    arr.push(vo)
                }
            }
            this.items = arr

        } else {
            this.items = rd.items
            if (this.isPage) {    // 分页数据
                this.page.total = rd.total
            }
        }

        this.loading = false
    }

    reload(page?: number) {
        if (!page || page == this.page.currentPage) {
            this.getList()
        } else {
            this.page.currentPage = page
            // 这里不需要查询数据，系统监听到当前页面变化，会自动查询数据
        }
    }

    search() {
        this.reload(1)
    }

    del({
            url,
            ids,
            isForce = false,
            message = ''
        }: {
        url: string,
        ids: Array<any>,
        isForce?: boolean,
        message?: string,
    }) {

        if (ids.length == 0) {
            ElMessageBox.alert("请选择要删除的记录")
            return
        }

        if (isForce && message == '') {
            message = message || `您将删除${ids.length}条记录，无法恢复，是否继续?`
        } else if (message == '') {
            message = message || `您将删除${ids.length}条记录，是否继续?`
        }

        ElMessageBox.confirm(
            message,
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }
        ).then(() => {
            let _data = this.items
            // let loading = ElLoading.service({text:'正在删除，请稍候'})
            simplePost(url, {ids: ids, is_force: isForce}).then((res) => {

                for (let id of ids) {
                    // @ts-ignore
                    let index = _data.findIndex(item => item.id == id)
                    _data.splice(index, 1)
                }
                this.items = _data

                // loading.close()
                msgSuccess("删除成功")

            })
        }).catch(() => {
        })

    }

    restore({url, ids, message = ''}: {
        url: string, ids: any[], message?: string
    }) {

        if (ids.length == 0) {
            ElMessageBox.alert("请选择要恢复的记录")
            return
        }

        message = message || `将恢复${ids.length}条数据，请谨慎操作。`
        ElMessageBox.confirm(
            message,
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }
        ).then(async () => {
            let _data = this.items
            // let loading = ElMessageBox.loading({text:'正在恢复，请稍候'})
            await simplePost(url, {ids: ids})
            for (let id of ids) {
                // @ts-ignore
                let index = _data.findIndex(item => item.id == id)
                _data.splice(index, 1)
            }
            this.items = _data
            // loading.close()
        }).catch(() => {
        })

    }
}
